package com.jbookshelf.beans;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.jbookshelf.dal.entities.Languages;
import com.jbookshelf.dal.providers.LanguagesDataProvider;

@Component
@Scope("request")
public class LanguagesBean {
	@Autowired
	LanguagesDataProvider dataProvider;

	private List<Languages> languages;
	private Languages selectedLanguage;

	private Languages newLanguage;

	public LanguagesBean() {
		newLanguage = new Languages();
	}

	public List<Languages> getLanguages() {
		if (languages == null) {
			languages = dataProvider.getLanguages();
		}
		return languages;
	}

	public Languages getSelectedLanguage() {
		return selectedLanguage;
	}

	public void setSelectedLanguage(Languages selectedLanguage) {
		this.selectedLanguage = selectedLanguage;
	}

	public void setLanguages(List<Languages> languages) {
		this.languages = languages;
	}

	public void setName(String name) {
		String validName;
		validName = name.substring(0, 1).toUpperCase()
				+ name.substring(1).toLowerCase();
		this.newLanguage.setName(validName);
	}

	public String getName() {
		return newLanguage.getName();
	}

	public void saveNewLanguage() {
		boolean exists = false;
		for (Languages l : dataProvider.getLanguages()) {
			if (l.getName().equals(newLanguage.getName())) {
				exists = true;
			}
		}
		if (exists) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage("Failed!",
					"The language already exists!"));
		} else
			dataProvider.insertLanguage(newLanguage);
		hideDialog();
		RequestContext.getCurrentInstance().update("languages_form");
	}

	public void showDialog() {
		final RequestContext context = RequestContext.getCurrentInstance();
		context.execute("nldlg.show()");

	}

	public void hideDialog() {
		final RequestContext context = RequestContext.getCurrentInstance();
		context.execute("nldlg.hide()");
	}

}
